package com.cslc.mp.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.cslc.mp.constant.MpInfo;
import com.cslc.mp.service.MessageService;
import com.cslc.mp.util.SignUtil;

/**
 * 核心请求处理类
 * @author keliangliang
 *
 */
public class CoreServlet extends HttpServlet {
	
	private static Logger logger = Logger.getLogger(CoreServlet.class.getName());
	private static final long serialVersionUID = 8756811780780811770L;
    /**
     * 验证url和token
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 微信加密签名 
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        PrintWriter out = response.getWriter();  
        if(signature == null || signature.length() <= 0)
        	logger.error("signature为空！");
        else {
        	logger.debug("开始校验signature :" + signature);
            // 通过检验 signature 对请求进行校验，若校验成功则原样返回 echostr，表示接入成功，否则接入失败
            if(SignUtil.checkSignature(signature, timestamp, nonce)) {
            	logger.debug("signature校验成功，返回echostr，接入成功");
            	out.print(echostr);
            }
            else {
            	logger.error("signature校验失败");
            }
        }    
        out.close();
        out = null;
	}

    /**
     * 用户向公众平台发信息,处理微信服务器发来的消息
     */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 调用核心业务类接收消息、处理消息
		String respMessage = MessageService.processRequest(request);
		logger.debug("返回给用户的消息： " + respMessage);
		// 响应消息
		PrintWriter out = response.getWriter();
		out.print(respMessage);
		out.close();
	}

}
